# _*_ coding: utf-8 _*_
"""
Time:     2024/9/4
Author:   2051261
File:     load.py
"""
import aiofiles
from datetime import datetime, timedelta
from pathlib import Path
import yaml
from apscheduler.triggers.interval import IntervalTrigger

from mine.scheduler.scheduler import scheduler_manager
from mine.project.log import log_manager
from extractor.flow.task_entry import TaskEntry
from extractor.const import ENV

current_path = Path(__file__)


def add_scheduler_job(task: TaskEntry):
    scheduler_manager.register_job(task.run, trigger=task.task_model.scheduler.trigger,
                                   job_id=task.task_model.task_name, **task.task_model.scheduler.trigger_params)


async def add_scheduler_write_jobs():
    def write_jobs_to_file():
        out_file = current_path.parent.parent.parent.parent.joinpath('log/register_tasks.yml')
        out_file.parent.mkdir(parents=True, exist_ok=True)
        job_list = scheduler_manager.get_register_jobs()
        with open(out_file, "w") as f:
            yaml.dump(job_list, f, default_flow_style=False)

    await scheduler_manager.register_job(write_jobs_to_file,
                                         trigger=IntervalTrigger(hours=1,
                                                                 start_date=datetime.now() + timedelta(minutes=10)),
                                         job_id=write_jobs_to_file.__name__)


async def initialize_log():
    log_path = current_path.parent.parent.parent.parent.joinpath('log')
    log_name = str(log_path.joinpath('app.log'))
    error_name = str(log_path.joinpath('error.log'))
    await log_manager.register(log_path, log_name, error_name)


async def read_yml(directory_path: Path):
    try:
        if not directory_path.exists():
            msg = f"File '{directory_path}' does not exist."
            log_manager.error(msg)
            raise FileNotFoundError(msg)
        async with aiofiles.open(directory_path, mode='r', encoding='utf-8') as file:
            content = await file.read()
            parsed_content = yaml.safe_load(content)
            if parsed_content is None:
                return []
            if not isinstance(parsed_content, list):
                msg = f"The content of file '{directory_path}' is not as expected. It should be a list."
                log_manager.error(msg)
                raise ValueError(msg)
            return parsed_content
    except Exception as e:
        raise e


async def get_default_paths() -> tuple[Path, Path]:
    base_path = current_path.parent.parent.parent.parent.joinpath('conf')
    with open(base_path.joinpath('env.txt'), 'r', encoding='utf-8') as file:
        env = file.readline().strip()
    if env.lower() == ENV.DEV:
        db_path = base_path.joinpath('db/dev')
    elif env.lower() == ENV.TEST:
        db_path = base_path.joinpath('db/test')
    elif env.lower() == ENV.ONLINE:
        db_path = base_path.joinpath('db/online')
    else:
        log_manager.error(f"Incorrect environment configuration: {env}, support env config: dev|test|online")
        raise
    return base_path.joinpath("tasks"), db_path
